package com.lxq.market.servlet.update;

import com.google.gson.JsonObject;
import com.lxq.market.model.Category;
import com.lxq.market.service.CategoryService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@WebServlet("/update/update_category")
public class UpdateCategoryServlet extends HttpServlet {

    CategoryService categoryService=CategoryService.getInstance();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        JsonObject jsonObject=new JsonObject();
        actionStrategy(action,req,jsonObject);
        resp.setContentType("application/json;charset=utf-8");
        resp.getOutputStream().write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
    }

    private void actionStrategy(String action,HttpServletRequest req,JsonObject jsonObject){
        if (action==null){
            jsonObject.addProperty("result",false);
            return;
        }
        if (action.equals("")){
            jsonObject.addProperty("result",false);
            return;
        }
        switch (action){
            case "update":update(req,jsonObject);break;
            case "add":add(req,jsonObject);break;
            case "delete":delete(req,jsonObject);break;
            default:jsonObject.addProperty("result",false);
        }
    }
    private void update(HttpServletRequest req,JsonObject jsonObject){
        String originCategoryName = req.getParameter("old_category_name");
        String newCategoryName = req.getParameter("new_category_name");
        String newCategoryDesc = req.getParameter("new_category_desc");
        Category category=new Category();
        category.setCategoryName(newCategoryName);
        category.setCategoryExplain(newCategoryDesc);
        boolean result=categoryService.updateCategory(category,originCategoryName);
        jsonObject.addProperty("result",result);
    }
    private void add(HttpServletRequest req,JsonObject jsonObject){
        String addCategoryName = req.getParameter("add_category_name");
        String addCategoryDesc = req.getParameter("add_category_desc");
        Category category=new Category();
        category.setCategoryExplain(addCategoryDesc);
        category.setCategoryName(addCategoryName);
        jsonObject.addProperty("result",categoryService.addCategory(category));
    }
    private void delete(HttpServletRequest req,JsonObject jsonObject){
        String delCategoryName = req.getParameter("del_category_name");
        jsonObject.addProperty("result",categoryService.delete(delCategoryName));
    }
}
